package com.li.springbootproject.controller.test;

import com.google.common.util.concurrent.RateLimiter;
import com.li.springbootproject.config.requestlimit.LimitFlag;
import com.li.springbootproject.config.requestlimit.counterlimit.FixedWindowCounterLimiting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 2021/12/26 10:45
 */
@RestController
@RequestMapping("/limit")
public class CounterLimitController {

    private static final Logger logger = LoggerFactory.getLogger(CounterLimitController.class);

    private final FixedWindowCounterLimiting limiting = new FixedWindowCounterLimiting(60, 100, TimeUnit.SECONDS);

    /**
     * 限流策略 ： 1秒钟2个请求
     */
    private final RateLimiter limiter = RateLimiter.create(1.0);

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @GetMapping("/test1")
    public String testOne() {
        if (limiting.count()) {
            return "Hello World!";
        }
        return "限流";
    }

    @GetMapping("/test2")
    public String testLimiter() {
        // 100 毫秒内，没拿到令牌，就直接进入服务降级
        boolean tryAcquire = limiter.tryAcquire(100, TimeUnit.MILLISECONDS);
        if (!tryAcquire) {
            logger.warn("进入服务降级，时间{}", LocalDateTime.now().format(formatter));
            return "当前排队人数较多，请稍后再试！";
        }
        logger.info("获取令牌成功，时间{}", LocalDateTime.now().format(formatter));
        return "请求成功";
    }

    @RequestMapping("/test3")
    @LimitFlag
    public String test3() {
        return "ok!";
    }

}
